package com.hc.testaudio.deletea.test1.ui;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;

import com.hc.testaudio.R;
import com.yc.yclibrary.base.YcAppCompatActivity;
import com.yc.yclibx.comment.YcLog;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.List;

import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Metadata;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.Spine;
import nl.siegmann.epublib.domain.SpineReference;
import nl.siegmann.epublib.domain.TOCReference;
import nl.siegmann.epublib.epub.EpubReader;

/**
 *
 */
public class EpubActivity extends YcAppCompatActivity {
    WebView mWebView;

    @Override
    protected int getLayoutId() {
        return R.layout.test_epub_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mWebView = findViewById(R.id.epubWeb);
        findViewById(R.id.epubBtn).setOnClickListener(v -> {
            scan();
        });
    }

    private void scan() {
        try {
            // find InputStream for book
            EpubReader reader = new EpubReader();
            InputStream epubInputStream = getAssets().open("test.epub");
            Book book = reader.readEpub(epubInputStream);
            //  book.getMetadata()获取书的元数据（Authors(作者)、title(标题)、contributors(贡献者)、封面等等）
            Metadata metadata = book.getMetadata();
            String bookInfo = "作者：" + metadata.getAuthors().get(0) +
                    "\n出版社：" + metadata.getPublishers().get(0) +
                    "\n出版时间：" + metadata.getDates().get(0).getValue() +
                    "\n书名：" + metadata.getTitles().get(0) +
                    "\n简介：" + metadata.getDescriptions().get(0) +
                    "\n语言：" + metadata.getLanguage();
            Log.i("bookInfo", bookInfo);

            // Log the book's title
            Log.i("epublib", "title: " + book.getTitle());

            // Log the book's coverimage property
            if (book.getCoverImage() != null && book.getCoverImage().getInputStream() != null) {
                Bitmap coverImage = BitmapFactory.decodeStream(book.getCoverImage().getInputStream());
                Log.i("epublib", "Coverimage is " + coverImage.getWidth() + " by " + coverImage.getHeight() + " pixels");
            } else {
                Log.i("epublib", "没有封面");
            }
            // 目录
            List<TOCReference> tocReferences = book.getTableOfContents().getTocReferences();
            for (TOCReference item : tocReferences) {
                YcLog.e("这是目录列表" + item.getTitle());
            }
            //读取书的内容，但是这种读取方式下，书的格式会乱，插图也无法显示
            List<Resource> list = book.getContents();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < list.size(); i++) {
                Resource res = list.get(i);
                byte[] resdata = res.getData();
                String str = new String(resdata, "utf-8");
                sb.append(str);
//                if (i == 0) {
//                    sb.append(" <img class=\"cover\" src=\"../Images/cover.jpg\"/>");
//                }
            }
            //用WebView显示书的内容,此时格式已经乱了
            //设置webView属性，能够执行javascript
            mWebView.getSettings().setJavaScriptEnabled(true);
            mWebView.loadDataWithBaseURL(null, "" + sb.toString(), "text/html", "utf-8", null);

            // 书籍的阅读顺序，是一个线性的顺序。通过Spine可以知道应该按照怎样的章节,顺序去阅读，
            // 并且通过Spine可以找到对应章节的内容。
            Spine spine = book.getSpine();
            List<SpineReference> spineReferences = spine.getSpineReferences();
            if (spineReferences != null && spineReferences.size() > 0) {
                for (int i = 0; i < spineReferences.size(); i++) {
                    Resource resource = spineReferences.get(i).getResource();//获取带章节信息的那个html页面
                    Log.i("SpineReference", "initView: ddd=" + resource.getId() + "  " + resource.getTitle() + "  " + resource.getSize() + " ");
                    byte[] data = resource.getData();//和 resource.getInputStream() 返回的都是html格式的文章内容，只不过读取方式不一样
                    String strHtml = bytes2Hex(data);
                    Log.i("SpineReference", "initView: strHtml= " + strHtml);
                    parseHtmlData(strHtml);
                }
            }
        } catch (IOException e) {
            Log.e("epublib", e.getMessage());
        }
    }

    public static String bytes2Hex(byte[] bs) {
        if (bs == null || bs.length <= 0) {
            return null;
        }
        Charset charset = Charset.defaultCharset();
        ByteBuffer buf = ByteBuffer.wrap(bs);
        CharBuffer cBuf = charset.decode(buf);
        return cBuf.toString();
    }

    /**
     * 解析html
     */
    private void parseHtmlData(String strHtml) {
        Document doc = Jsoup.parse(strHtml);
        Log.i("parseHtmlData", "parseHtmlData:  doc.title();=" + doc.title());
        Elements eles = doc.getElementsByTag("a"); // a标签
        // 遍历Elements的每个Element
//        EpubBean epubBean;
        for (Element link : eles) {
            String linkHref = link.attr("href"); // a标签的href属性
            String text = link.text();
//            epubBean = new EpubBean();
//            epubBean.href = linkHref;
//            epubBean.tilte = text;
//            indexTitleList.add(epubBean);
            Log.i("parseHtmlData", "parseHtmlData: linkHref=" + linkHref + " tilte=" + text);
        }
    }

    /**
     * Recursively Log the Table of Contents
     *
     * @param tocReferences
     * @param depth
     */
    private void logTableOfContents(List<TOCReference> tocReferences, int depth) {
        if (tocReferences == null) {
            return;
        }
        for (TOCReference tocReference : tocReferences) {
            StringBuilder tocString = new StringBuilder();
            for (int i = 0; i < depth; i++) {
                tocString.append("\t");
            }
            tocString.append(tocReference.getTitle());
            Log.i("aaa", tocString.toString());

            logTableOfContents(tocReference.getChildren(), depth + 1);
        }

    }
}